<?php

namespace platform;

use GuzzleHttp\Client;
use redis\RedisTools;
use think\facade\Log;

/**
 * 码友拓客
 */
class MaYouPlatform
{
    /**
     * 接口请求地址
     * @var string
     */
    public static $url = 'http://www.mytk.cc/api/open/task/getQrcode';

    /**
     * appid
     * @var string
     */
    public static $appid = '718cc4d2068841fd84b650b6650222f7';

    /**
     * api密钥
     * @var string
     */
    public static $key = '1df1dbc06c3d45e1a77ef8f3ad37ccd13vyz0hiygy6yx6nqivhs2gt7sqi8zvrn';

    /**
     * 取号接口
     * @param $user
     */
    public function queryInterface($user,$mac_id,$url)
    {
        $sex = $user['sex']==0?rand(1,2):$user['sex'];
        $time = time();
        $k = self::$key;
        $response_message = md5("{$user['id']}{$k}{$time}");
        $data = [
            'appid'=>self::$appid,
            'time'=>$time,
            'openid'=>$user['openid'],
            'state'=>$response_message,
            'redirectUrl'=>$url,
            'callbackUrl'=>'https://'.$_SERVER['HTTP_HOST'].'/callback/MaYouAfterNotify',
//            'province'=>'广东省',
//            'city'=>'深圳市',
            'nickname'=>$user['nickname'],
            'gender'=>$sex,
        ];
        Log::write($data, '码友请求信息信息');
        $data['sign'] = md5($data['appid'].$data['openid'].$data['time'].self::$key);
        $http = new Client(['headers' => [
            "Content-type" => 'application/json'
        ]]);
        $response = $http->post(self::$url, [
            'json' => $data
        ]);
        //返回值
        if($response->getStatusCode() != 200){
            throw new \Exception("网络请求错误");
        }
        $data = $response->getBody()->getContents();
        Log::write($data, '码友返回信息');
        $data = json_decode($data,true);
        if($data['code'] != 200){
            throw new \Exception("获取失败");
        }
        if(!isset($data['data'])) throw new \Exception("码友取号失败");
        if(empty($data['data'])) throw new \Exception("码友取号失败");
        //设置请求数据缓存
        $oRedis = RedisTools::getInstance(config('cache.stores.redis'), 0)->getRedis();
        $times = $time+1800;
        $h = date('H',$times);
        $i = date('i',$times);
        $s = date('s',$times);
        $expireTime=mktime($h,$i,$s,date("m"),date("d"),date("Y"));
        $key = 'my:'.$response_message;
        $oRedis->set($key,$user['unionid']);
        $oRedis->expireAt($key,$expireTime);
        return $data['data'];
    }
}